define(window.backboneCommon.getViewDefine("report.detail"), function ($,require,Collection,tpl) {
    var backboneView= Backbone.View.extend({
        events: {
            "click #chart_btnGroup .btn": "changeChart",
            "click #btn_download": "downloadExcel",
            "click #panel_reportMenu a": "changeMenu"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.customer=this.model.get("modelCustomer");
            this.listenTo(this.modelAttach.customer, 'bind:Info', this.bindAdvertiser);
            this.listenTo(this.model, 'bind:ReportDetail', this.bindReportData);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(id){
            this.elementModel={};
            this.extObject={};
            this.elementModel.chart=$("#chart_report");
            this.elementModel.menu=$("#panel_reportMenu");
            this.pageData={isReportShowIng:true,customerId:id};
            this.pageData.initChartDefault=this.model.get("chartDefault");
            this.pageData.infoChartTabsQueue= $.ExtCommon.getJsonClone(this.model.get("chartQueue"));
            this._initBodyMain();
        },
        _initBodyMain:function(){
            this._initAssistCallback();
            this._bindDateDay();
            this._bindDateRange();
            this.collection.initAfterDetail(this.pageData.customerId);
            this._filterReportData();
            $.ExtAssist.urlParam.setUrl();
        },
        _initAssistCallback:function(){
            var self=this;
            $.ExtAssist.winResize.callback("ReportDetail",function(){
                if(self.pageData.chartReport){
                    self._bindChartData()
                }
            });
        },
        bindAdvertiser:function () {
            var result=this.modelAttach.customer.get("dataInfo");
            $("#sp_advertiserName").attr("title",result.res.data.name).text(result.res.data.name);
        },
        _bindDateDay:function () {
            var self=this;
            $("#txt_day").ExtDatePicker({initValue:$.ExtMoment.initAdd(),
                changeCallback: function () {self._filterReportData()}
            });
        },
        _bindDateRange:function (options) {
            var self=this;
            if(self.extObject.timeRang){
                self.extObject.timeRang.setValue(options.startDate,options.endDate);
            }else{
                self.extObject.timeRang=$("#txt_range").ExtDatePicker({type:"range",
                    addQuick:{"本月": [$.ExtMoment.initMoment().startOf('month'), $.ExtMoment.initMoment()]},
                    maxDate:$.ExtMoment.initMoment(),
                    startValue:$.ExtMoment.initAdd(-7),endValue:$.ExtMoment.initAdd(-1),
                    changeCallback: function () {self._filterReportData()}
                });
            }
        },
        _filterReportData:function(){
            this.pageData.tabs={};
            this.pageData.chartReport={};
            this._initReportData();
        },
        _initReportData:function () {
            if (this.pageData.isReportShowIng) {
                this.pageData.isReportShowIng = false;
                this.pageData.loadInfo={place: "box", boxId: ".panel-loading-multiple", height: 400, type: "circle", dataListName: "list"};
                $.ExtAjax.initLoadStart(this.pageData.loadInfo);
                var type=this._getReportType();
                var ajaxParam=this.getAjaxInfo(type);
                this.collection.getReportList(type,ajaxParam);
            }
        },
        getAjaxInfo:function(type){
            var arrTime = [];
            if(type==="hour"){
                var timeDay=$("#txt_day").val();
                arrTime=[timeDay,timeDay];
            }else{
                if(this.extObject.timeRang){
                    arrTime=this.extObject.timeRang.getValue();
                }
            }
            return {customerId:this.pageData.customerId,startTime:arrTime[0], endTime:arrTime[1]};
        },
        bindReportData:function(){
            var self = this;
            var result=self.model.get("dataReportDetail");
            var type=result.req.type;
            var options = self._getReportOption();
            if(result.res.success){
                $.ExtReport.initBind(options, result.res.data.list, function (resJson) {
                    resJson.totleTable=result.res.data.total;
                    self.pageData.tabs[type]=resJson;
                    self.pageData.chartReport =self._getReportData(resJson);
                    self._bindChartData();
                    if(self.pageData.chartReport.tableData.length===0){
                        $.ExtAjax.initLoadEnd({place: "box", boxId: "#panel_table_chart", dataListLength:1})
                    }else{
                        self.pageData.loadInfo.dataListLength=self.pageData.chartReport.tableData.length;
                        $.ExtAjax.initLoadEnd(self.pageData.loadInfo);
                    }
                    self._bindTable(type,{data: self.pageData.chartReport.tableData, orderIndex: options.table.sortIndex});
                    self.pageData.isReportShowIng = true;
                });
            }else{
                if($.ExtCommon.isCheckUndefined(self.pageData.chartReport.original)){
                    self.pageData.chartReport.original=[];
                    self.pageData.chartReport.original.list=[];
                }
                self._bindChartData();
                $.ExtAjax.initLoadEnd({place: "box", boxId: "#panel_table_chart", dataListLength:1});
                self._bindTable(type,{data: self.pageData.chartReport.tableData,orderIndex:options.table.sortIndex});
                self.pageData.isReportShowIng = true;
                $.ExtNotify.error("报告数据获取失败："+result.res.msg)
            }
        },
        _getReportData:function(resJson){
            var json=$.ExtCommon.getJsonClone(resJson);
            json.infoChartTabsQueue = this.pageData.infoChartTabsQueue;
            json.infoChartDefault = this.pageData.initChartDefault;
            json.tableData = resJson.original.list.length > 0 ? resJson.original.list : [];
            return json;
        },
        _bindChartData:function(){
            if(this.pageData.chartReport.original.list.length>0){
                this.elementModel.chart.show().next().hide();
                var chartOption=$.ExtReport.getChartOption(this.pageData.chartReport);
                $.ExtReport.initECharts(this.elementModel.chart[0], chartOption);
            }else{
                $.ExtAjax.initLoadEnd({place: "box", boxId: "#chart_report", dataListLength:0});
            }
        },
        _getReportType:function () {
            var tabsData=this.elementModel.menu.find(".chart-active").data();
            return $.ExtCommon.isCheckEmpty(tabsData["selectValue"])?"":tabsData["selectValue"];
        },
        _getReportOption:function(){
            var self=this;
            var tabsData=this.elementModel.menu.find(".chart-active").data();
            var tableSortIndex=$.ExtCommon.isCheckEmpty(tabsData["tableSortIndex"])?0:tabsData["tableSortIndex"];
            var type=this._getReportType();
            var chartSeriesType= $.ExtCommon.isCheckEmpty(tabsData.chartType)?self.initChartDefault.chartType :tabsData.chartType;
            var chartXAxisLen = type === "hour" ? -1 :($.ExtCommon.isCheckEmpty(tabsData["chartXAxisLen"])?10:parseInt(tabsData["chartXAxisLen"]));
            var chartXOther=false;
            var charByDesc = type === "day"?true:($.ExtCommon.isCheckEmpty(tabsData["chartByDesc"])?false:tabsData["chartByDesc"]);
            var defKeyword="description";
            var chartKeyword=$.ExtCommon.isCheckEmpty(tabsData["chartKeyword"])?defKeyword:tabsData["chartKeyword"];
            return {element:this.elementModel.chart, type: type,
                table:{sortIndex:parseInt(tableSortIndex)},
                chart: {infoDefault:this.pageData.initChartDefault, hoverTitle:defKeyword, keyword: chartKeyword, seriesType: chartSeriesType, xAxisLen: chartXAxisLen, xOther: chartXOther, isDesc: charByDesc}
            };
        },
        _bindTable: function (type,tableJson) {
            var self=this;
            var elementTableListChart= $("#tb_list");
            if(self.tableReport) elementTableListChart.ExtDataTable("destroy");
            self.tableReport=elementTableListChart.ExtDataTable({
                paging: false,
                serverSide:false,
                bInfo:false,
                ordering:true,
                order: [[ tableJson.orderIndex, "desc" ]],
                columns: [
                    {data: "description",class:"w-min-100" },
                    {data: "pv",class:"w-120 num-int  text-right td-sorting"},
                    {data: "click",class:"w-120 num-int text-right td-sorting"},
                    {data: "cr",class:"w-120 num-float2 text-right td-sorting"},
                    {data: "price",class:"w-120 num-float2 text-right td-sorting"},
                    {data: "cost",class:"w-120 num-float2 text-right td-sorting"}
                ],
                infoExt:{data:tableJson.data},
                createdRow: function (row, data) {
                    var keyValue="";
                    switch(type){
                        case "hour":
                            keyValue=$.ExtCommon.getHourInterval(parseInt(data.description));
                            break;
                        case "strategy":
                        case "strategyGroup":
                            keyValue=data.id+" - "+data.description;
                            break;
                    }
                    if(keyValue.length>0)  $('td', row).eq(0).html(keyValue);
                },
                drawCallback: function () {
                    if(self.pageData.chartReport.original.list.length>0) {
                        var totalInfo=self.pageData.chartReport.totleTable;
                        var trTotal = $.ExtCommon.getStringConnect('<tr role="row" class="tr-total">' +
                            '<td class="sorting_1">总计</td>' +
                            '<td class=" num-int  text-right td-sorting">{0}</td>' +
                            '<td class=" num-int text-right td-sorting">{1}</td>' +
                            '<td class=" num-float2 text-right td-sorting">{2}</td>' +
                            '<td class=" num-float2 text-right td-sorting">{3}</td>' +
                            '<td class=" num-float2 text-right td-sorting">{4}</td></tr>',
                            [totalInfo.pv,totalInfo.click,totalInfo.cr,totalInfo.price,totalInfo.cost]) ;
                        elementTableListChart.find("tbody").prepend(trTotal);
                    }
                    $.ExtNumeric.initAll();
                }
            });
        },
        changeChart:function (e) {
            $.ExtNotify.destroy();
            var value=$(e.currentTarget).val();
            var arrValue=$.ExtReport.getChartTabsQueue(value,this.pageData.chartReport);
            if(arrValue.length>0){
                var chartBtnGroup=$("#chart_btnGroup");
                chartBtnGroup.find(".btn-default").toggleClass("btn-white btn-default");
                $.each(arrValue,function(i,info){
                    chartBtnGroup.find("button[value='"+info+"']").toggleClass("btn-white btn-default");
                });
                this._bindChartData();
            }else{
                $.ExtNotify.error("必须保留一个!");
            }
        },
        _getTimeRangeValue:function(){
            var arrTime =this.extObject.timeRang.getValue();
            return arrTime.length===2 ?{startTime:arrTime[0],endTime:arrTime[1]}:{startTime:arrTime[0],endTime:arrTime[0]};
        },
        downloadExcel:function(){
            var type=this._getReportType();
            var param=this._getTimeRangeValue();
            this.collection.downloadExcelByType(type,param)
        },
        changeMenu:function (e) {
            var self=this;
            var _this=$(e.currentTarget);
            var _thisNext=_this.next();
            if(_thisNext.is("ul.list-unstyled")){
                if(_thisNext.is(":visible")){
                    _this.find(".icon-operate").addClass("rotate-180");
                    _thisNext.slideUp();
                }else{
                    _this.find(".icon-operate").removeClass("rotate-180");
                    _thisNext.slideDown();
                }
            }else{
                if(!_this.hasClass("chart-active")) {
                    if (self.pageData.isReportShowIng) {
                        $.ExtNotify.destroy();
                        var arrTitle = [];
                        arrTitle.push(_this.text());
                        _this.closest("#panel_reportMenu").find(".active,.chart-active").removeClass("active chart-active");
                        var _thisUL = _this.closest("ul");
                        if (_thisUL.hasClass("list-unstyled")) {
                            _this.addClass("chart-active").parent().addClass("active");
                            var thisPrev = _thisUL.prev();
                            thisPrev.addClass("active");
                            arrTitle.push(thisPrev.text());
                            arrTitle.push(_thisUL.parent().prevAll(".menu-title").eq(0).text());
                        } else {
                            _this.addClass("active chart-active");
                            arrTitle.push(_this.parent().prevAll(".menu-title").eq(0).text());
                        }
                        $("#th_menuName").text(arrTitle[0]);
                        arrTitle.reverse();
                        $("#sp_reportTitle").text(arrTitle.join("-"));
                        var type=_this.data("selectValue");
                        if (type=== "hour") {
                            $(".timeRange").hide();
                            $(".timeDay").show()
                        } else {
                            $(".timeRange").show();
                            $(".timeDay").hide();
                        }
                        var optionsTimeRange={};
                        var maxDate=["city","gender","age"].indexOf(type)>-1?$.ExtMoment.initFormat({value:$.ExtMoment.initSubtract(1)}):false;
                        if(self.extObject.timeRang){
                            var arrTime=self.extObject.timeRang.getValue();
                            optionsTimeRange.startDate=arrTime[0];
                            optionsTimeRange.endDate=arrTime[1];
                            if(maxDate){
                                optionsTimeRange.startDate=$.ExtMoment.timeDiff(arrTime[0],maxDate)>0?arrTime[0]:maxDate;
                                optionsTimeRange.endDate=$.ExtMoment.timeDiff(arrTime[1],maxDate)>0?arrTime[1]:maxDate;
                            }
                        }
                        optionsTimeRange.maxDate=maxDate?new Date(maxDate+" 23:59:59"):false;
                        self._bindDateRange(optionsTimeRange);
                        self.collection.getReportList(type,self.getAjaxInfo());
                    }
                    else {
                        $.ExtNotify.warning("操作过于频繁，请稍后查询");
                    }
                }
            }
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({ el: "#container_body",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function (param) {
            var id=param?param[0]:null;
            this.view.initMain(id);
        }
    };
    return viewModel;
});